package com.demo.generator.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: demo
 * @description:
 * @author: fbl
 * @create: 2021-12-23 14:28
 **/
@RestController
@RequestMapping("/word")
@Api(value = "WordTestController", tags = "word生成测试类")
public class WordTestController {

    @Resource(name = "wordConfiguration")
    private Configuration wordConfiguration;

    /**
     * 生成word测试
     */
    @PostMapping("/export-word")
    @ApiOperation(value = "生成word")
    public void exportWord(HttpServletResponse response) {


        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("name", "范保林");
        dataModel.put("address", "平顶山");

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=books.doc");
        //加载模板
        try {
            Template template = wordConfiguration.getTemplate("word_template.ftl", "utf-8");
            template.process(dataModel, response.getWriter());//response的Writer不需要我们手动关，tomcat会帮我们关的
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Data
    private class Entpr {
        private String name;
        private String address;

    }
}
